/**********************************************
 * 
 * File Name				:	TemplateServiceImpl.java
 * 
 * Last Changed Date		: 	$Date: 2009-08-01 11:12:53 +0800 (星期六, 01 八月 2009) $
 * 
 * Last Changed Revision	:	$Revision: 86 $
 * 
 * Last Changed Author		:	$Author: cfanboy $
 * 
 * File Header URL			:	$HeadURL: svn://www.svnhost.cn/Busi-Building/code/branch/src/com/busibuilding/common/templates/TemplateServiceImpl.java $
 * 
 * ********************************************
 */

package com.busibuilding.common.templates;

import java.io.IOException;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import com.busibuilding.common.exceptions.ServiceException;

import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * Class Name: TemplateServiceImpl.java
 * Description: Generate the template content via value passed.
 * @author YU Zhipeng
 * @version 1.0
 * @since 1.0
 * Date: 2009-7-15
 */

public class TemplateServiceImpl implements TemplateService {
	private static Logger logger = LogManager.getLogger(TemplateServiceImpl.class);
	
	private FreeMarkerConfigurer fmConfig;
	
	public void setFmConfig(FreeMarkerConfigurer fmConfig) {
		this.fmConfig = fmConfig;
	}

	/**
	 * Generate the template content.
	 * @param templateName
	 * @param valueMap
	 * @return String
	 * @throws ServiceException
	 */
	@Override
	public String generateTemplateContent(String templateName,
			Map<String, Object> valueMap) throws ServiceException {
		Template tpl = null;
		String content = null;
		try {
			tpl = fmConfig.getConfiguration().getTemplate(templateName);
			content = FreeMarkerTemplateUtils.processTemplateIntoString(tpl, valueMap);
		} catch (IOException e) {
			logger.fatal(e.getMessage() + "\n" + e);
			throw new ServiceException(COMMON_ERROR_CODE_TEMPLATE_GET_TEMPLATE, e);
		} catch (TemplateException e) {
			logger.fatal(e.getMessage() + "\n" + e);
			throw new ServiceException(COMMON_ERROR_CODE_TEMPLATE_PROCESS_TEMPLATE, e);
		}
		
		return content;
	}

}
